package com.hujiang.basic.search.fullindex;

import com.hujiang.basic.framework.rest.common.BaseService;
import com.hujiang.basic.search.handler.impl.model.FullIndexTask;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.List;

@Slf4j
@Repository
public class TaskDao extends BaseService<FullIndexTask> {

    private static final String NAMESPACE = "fullIndex";

    @Override
    protected String namespace() {
        return NAMESPACE;
    }

    public int createTask(FullIndexTask task) {
        return insert(NAMESPACE, "createTask", task);
    }

    public List<FullIndexTask> findSpareTask() {
        return query(NAMESPACE, "findSpareTask", null);
    }

    public List<FullIndexTask> findExpiredTask() {
        return query(NAMESPACE, "findExpiredTask", null);
    }

    public void updateTask(FullIndexTask task) {
        if (StringUtils.isNotEmpty(task.getMessage())) {
            String message = StringUtils.substring(task.getMessage(), 0, 200);
            task.setMessage(message);
        }

        update(NAMESPACE, "updateTask", task);
    }

    public int acceptTask(FullIndexTask task) {
        return update(NAMESPACE, "acceptTask", task);
    }

    public String getOwner(String index) {
        List<FullIndexTask> tasks = query(NAMESPACE, "getOwner", index);
        if (CollectionUtils.isEmpty(tasks)) {
            return null;
        }
        // 取最近一条记录里的owner
        return tasks.get(tasks.size() - 1).getOwner();
    }
}
